<template>
  <!-- v-loading="true" -->
  <div>

    <pageSearch :searchFormConfig="searchFormConfig" @searchSubmit="searchSubmit" />
    <pageTable :tableData="tableData" :tableInit="params.tableInit" @sizeChange="sizeChange"
      @currentChange="currentChange" @exportFn="exportExcel" v-loading="loading" @pageAdd="openDialogFn('新增')">
      <template #level="{ row }">
        {{ filterStatusName(row.level) }}
      </template>
      <template #operation="{ row }">
        <el-button type="primary" link @click="openDialogFn('编辑', row)">编辑</el-button>
        <el-popconfirm title="确认要删除吗?" @confirm="delData(row.id)">
          <template #reference>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>



    </pageTable>

    <Dialog width="50%" top="20vh" ref="DialogRef" :title="typeText" @submit="submitForm(ruleFormRef)"
      @onclose="resetForm(ruleFormRef)">
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">

        <el-row :gutter="20">


          <el-col :span="24">
            <el-form-item label="支持文件" v-if='!DialoLoading' prop="linkList">
              <uploadFiles v-model="ruleForm.linkList" @onPreviewFn="onPreviewFN" type="all"></uploadFiles>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="支持软件名字" prop="name" v-if='!DialoLoading'>
              <el-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入描述" type="textarea" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="简介" prop="scopes" v-if='!DialoLoading'>
              <el-input v-model="ruleForm.scopes" autocomplete="off" placeholder="请输入描述" type="textarea" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="描述" prop="list">
              <el-row class="w-full">
                <el-col class="mb-4" :span="24" v-for="(item, index) in ruleForm.list" :key="index">
                  <el-input v-model="item.description" autocomplete="off" placeholder="请输入描述" />
                </el-col>
                <el-col :span="24">
                  <el-button @click="addapplicationVersionClassDescriptions">添加新描述</el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-col>



          <el-col :span="24">
            <el-form-item label="文件封面" prop="imageList" v-if='!DialoLoading'>
              <LTUpload tip="建议图片尺寸 600*400" v-model="ruleForm.imageList" :limit="1"></LTUpload>
            </el-form-item>
          </el-col>



          <el-col :span="24">
            <el-form-item label="文档权限" prop="level">
              <el-select style="width: 20%" v-model="ruleForm.level" placeholder="请选择">
                <el-option v-for="option in filesStatus" :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
            <el-form-item label="评估板描述" prop="name">
              <el-row class="w-full">
                <el-col :span="24">
                  <el-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入评估板描述" />
                </el-col>
                <el-col :span="24" class="mt-4">
                  <el-button>添加新描述</el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-col> -->

        </el-row>
      </el-form>
    </Dialog>

    <el-dialog v-model="dialogTableVisible" title="预览">
      <pdfPage v-if="pdfUrl" :source='pdfUrl'></pdfPage>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pageTable from "@/components/base-ui/page-table";
import pageSearch from "@/components/base-ui/page-search";
import Dialog from "@/components/base-ui/dialog";
import { reactive, ref, computed } from 'vue'
import type { FormInstance, FormRules, UploadUserFile, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox, genFileId } from 'element-plus'
import { clone } from "@pureadmin/utils";
import { randomNumber } from '@/utils/xwCommon'
import { usepageTable } from '@/components/base-ui/page-table/usePageTable'
import pdfPage from "@/components/base-ui/pdf";
import uploadFiles from '@/components/base-ui/uploadFiles'
import { message } from "@/utils/message";
import { getPicImg, geturlneeddl } from '@/api/upload'
import { sjcyzcrjselfzwjpage, sjcyzcrjselfzwjbyid, sjcyzcrjupdatefzwj, sjcyzcrjdelproductfzwj, sjcyzcrjinsertfzwj } from '@/api/supportsoftware'
import { tableInit } from "./config/supportTable.config";
import { searchFormConfig } from "./config/supportSearch.config";
import LTUpload from '@/components/base-ui/upload'

const {
  exportExcel,
  tableData,
  getData,
  params,
  loading,
  sizeChange,
  currentChange,
  delData,
  searchSubmit,
  DialogRef,
  openDialog,
  filesStatus,
  filterStatusName
} = usepageTable({
  tableInit,
  getRes: sjcyzcrjselfzwjpage,
  delRes: sjcyzcrjdelproductfzwj,

})

getData()

const DialoLoading = ref(false)

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  // image: '',
  level: '',
  name: '',
  wjid: '',
  scopes: '',
  linkList: [],
  list: [],
  wjname: '',
  id: '',
  imageList: [],
  image: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  level: [{ required: true, message: '请选择文件权限', trigger: 'blur' }],
  linkList: [{ required: true, message: '请上传文件', trigger: 'blur' }],
  scopes: [{ required: true, message: '请填写简介', trigger: 'blur' }],
  name: [{ required: true, message: '请填写软件名字', trigger: 'blur' }],
  imageList: [{ required: true, message: '请上传封面', trigger: 'blur' }],
})
const typeText = ref('')
const openDialogFn = (text, row) => {
  DialoLoading.value = true
  typeText.value = text
  if (row) {
    sjcyzcrjselfzwjbyid(row.id).then(res => {
      const temporary = clone(res.result, true);
      Object.keys(ruleForm).forEach((key) => ruleForm[key] = temporary[key])
      ruleForm.linkList = [{
        name: temporary.wjname,
        url: temporary.wjid,
      }]
      ruleForm.imageList = [{
        name: '图片',
        url: getPicImg(temporary.image),
      }]



      ruleForm.list = temporary.list.map(v => {
        return {
          description: v
        }
      })

      console.log(ruleForm, 'ruleForm')
      openDialog()
      DialoLoading.value = false

    })
  } else {
    openDialog()
    DialoLoading.value = false

  }
}


const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      ruleForm.wjid = ruleForm.linkList[0]?.response?.data?.result[0]?.uuid ?? ruleForm.wjid
      ruleForm.image = ruleForm.imageList[0]?.response?.data?.result[0]?.uuid ?? ruleForm.image
      ruleForm.wjname = ruleForm.linkList[0].name ?? ruleForm.wjname
      let filterArray = ruleForm.list.filter(v => v.description);
      ruleForm.list = filterArray.map(v => v.description)

      let fn = typeText.value == '新增' ? sjcyzcrjinsertfzwj : sjcyzcrjupdatefzwj
      fn(ruleForm).then(() => {
        DialogRef.value.close()
        message(`${typeText.value}成功`, {
          type: 'success'
        });
        getData()
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()

  ruleForm.level = ''
  ruleForm.name = ''
  ruleForm.wjid = ''
  ruleForm.linkList = []
  ruleForm.list = []
  ruleForm.scopes = ''
  ruleForm.wjname = ''
  ruleForm.id = ''
}


const addapplicationVersionClassDescriptions = () => {
  ruleForm.list.push({
    description: ''
  })
}




const dialogTableVisible = ref(false)
const pdfUrl = ref('')
const onPreviewFN = (e) => {
  console.log(e)
  // pdfUrl.value = geturlneeddl(e)
  if (e.startsWith('http')) {
    pdfUrl.value = e
  } else {
    pdfUrl.value = geturlneeddl(e)
  }
  return window.open(pdfUrl.value)
  dialogTableVisible.value = true
}

</script>

<style scoped></style>
